<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-07 17:28:50
 * @LastEditTime: 2022-04-07 17:40:10
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 录音
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>录音</title>
</head>

<body>
  <audio controls class="audio-player"></audio>
  <button id="btn">开始录音</button>
  <button id="btn2">结束</button>
</body>
<script>
  const btn = document.getElementById('btn')
  btn.addEventListener('click', async () => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    const mediaRecorder = new MediaRecorder(stream)
    let chunks = []
    mediaRecorder.addEventListener('dataavailable', (e) => {
      console.log('开始录音');
      chunks.push(e.data)
    })
    mediaRecorder.addEventListener('stop', () => {
      const audio = document.querySelector('audio')
      var blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
      var audioURL = window.URL.createObjectURL(blob);
      audio.src = audioURL;
    })
    mediaRecorder.start();

    const btn2 = document.getElementById('btn2')
    btn2.addEventListener('click',()=>{
      console.log('结束录音');
      mediaRecorder.stop();
    })
  })
</script>

</html>